package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApArticleCollectionService;
import com.heima.model.article.dtos.ApArticleCollectDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.dtos.IsCollectionDto;
import com.heima.model.behavior.pojos.ApArticleUnlike;
import com.heima.utils.common.WmThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
@Slf4j
public class ApArticleCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApArticleCollectionService {

    private final ApCollectionMapper apCollectionMapper;

    @Override
    public void collect(ApArticleCollectDto apArticleCollectDto) {
        /* 进行数据的填充 */
        ApCollection apCollection = new ApCollection();
        apCollection.setEntryId(Long.valueOf(WmThreadLocalUtil.getUser().getId()));  // 当前用户 id
        apCollection.setArticleId(apArticleCollectDto.getEntryId());  // 文章 id
        apCollection.setType(apArticleCollectDto.getType());
        apCollection.setCollectionTime(LocalDateTime.now());
        apCollection.setPublishTime(apArticleCollectDto.getPublishTime());

        LambdaQueryWrapper<ApCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApCollection::getEntryId, apCollection.getEntryId())  // 当前用户 id 相同
                .eq(ApCollection::getArticleId, apArticleCollectDto.getEntryId());  // 当前文章 id 相同

        if(apArticleCollectDto.getOperation() == 0) {  // 如果操作类型为 0(收藏)
            apCollectionMapper.insert(apCollection);
        } else if (apArticleCollectDto.getOperation() == 1) {  // 如果传入类型为 1(取消收藏)
            apCollectionMapper.delete(wrapper);
        }

    }

    @Override
    public Boolean isCollection(IsCollectionDto isCollectionDto) {
        LambdaQueryWrapper<ApCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApCollection::getEntryId, isCollectionDto.getUserId())
                .eq(ApCollection::getArticleId, isCollectionDto.getArticleId());

        ApCollection apCollection = apCollectionMapper.selectOne(wrapper);
        return apCollection != null;
    }
}
